
/**
 * 逻辑异常封装类
 */
class LogicError extends Error {
  /**
   * 构造函数
   * @param {Object} params
   */
  constructor({
    code = 100001,
    msg = 'Unknow error',
    comment,
    data = null,
    clientError = false,
    status = 200,
  } = {}) {
    super(msg);
    this.message = msg;
    this.msg = msg;
    this.comment = comment || msg;
    this.code = code;
    this.data = data;
    this.clientError = clientError;
    this.status = status;
  }

  toString() {
    return `error message  [code: ${this.code}, message: ${this.message}, data: ${JSON.stringify(this.data)}, comment: ${this.comment}]`;
  }
}

module.exports = {
  success({ code = 0, msg = 'ok', data } = {}) {
    this.body = {
      code,
      msg,
      data,
    };
  },
  throwError({ code, msg, data }) {
    throw new LogicError({
      code, msg, data,
    });
  },
  throwDBError() {
    throw new LogicError({
      code: 100006,
      msg: 'DB ERROR',
    });
  },
};
